package.cpath = "luaclib/?.so;3rd/lua-cjson/?.so;"
package.path = "lualib/?.lua;3rd/json/?.lua;niuniu/?.lua"

local socket = require "clientsocket"
local json   = require "cjson"

local packdeal = {}

-- notice: we use 2 bytes save pack_len in pack head

function packdeal.send_package(client_fd, ack)
    local pack = json.encode(ack)

    --print("send: "..pack)

    local size = #pack
    local high = size>>8
    local low = size - (high<<8)
    local package = string.char(high)..string.char(low)..pack

    socket.send(client_fd, package)
end

function packdeal.unpack_package(text)
    local size = #text
    if size < 2 then
        return nil
    end
    local s = text:byte(1) * 256 + text:byte(2) -- s == pack_len -> size == s + 2
    if size < s+2 then
        return nil
    end

    return json.decode(text:sub(3,2+s))
end

return packdeal
